//import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
//import * as io from 'socket.io-client';
import * as io from 'socket.io-client/dist/socket.io.js';
import {CMD } from '../cid'

import { Injectable } from '@angular/core';

@Injectable()
export class ChatService {
  //  private url = 'http://localhost:3000';
    private socket:any;
    res = {
        tag:'',
        data:{}
    };

    constructor() {
       // this.socket = io();
    }

    sendLoginMessage(message:any){
        console.log('sendLoginMessage---');
        this.socket.emit(CMD.addUser.CNAME, message);
    }

    sendChatMessage(message:any){
        console.log('sendChatMessage---');
        this.socket.emit(CMD.addMessage.CNAME, message);
    }

    getMessages() {
        //noinspection UnnecessaryLocalVariableJS
        let observable = new Observable(observer => {
            this.socket = io();
            this.socket.on(CMD.userAddingResult.CNAME, (data:any) => {
                console.log('用户登陆的结果---');
                console.dir(data);

                observer.next(data);
            });

            this.socket.on(CMD.userAdded.CNAME, (data:any) => {
                console.log('userAdded---');
                console.dir(data);

                observer.next(data);
            });

            this.socket.on(CMD.allUser.CNAME, (data:any) => {

                console.log('allUser---');
                console.dir(data);

                observer.next(data);
            });

            this.socket.on(CMD.userRemoved.CNAME, (data:any) => {
                console.log('userRemoved---');
                console.dir(data);
                observer.next(data);
            });

            this.socket.on(CMD.messageAdded.CNAME, (data:any) => {
                console.log('messageAdded---');
                console.dir(data);
                observer.next(data);
            });

            this.socket.on(CMD.connect.CNAME, (data:any) => {
                console.log('connect---');
                // connect 没有data ,undefined
                console.dir(data);

                observer.next(data);
            });

            //别人 disconnnet 我怎么收到了？先去掉监控

            this.socket.on(CMD.disconnect.CNAME, (data:any) => {
                //服务端自己断开之前会发送一个 disconnect ，data = transport close
                //然后，客户端就一直 ERR_CONNECTION_REFUSED，等待重连

                console.log('disconnect ??? ---');
                console.dir(data);
                observer.next(data);
            });

            return () => {
                console.log('9999999999999---');
                this.socket.disconnect();
            };
        });
        return observable;
    }



}